<template>
  <div class="box">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/index/art-list' }"
            >文档列表</el-breadcrumb-item
          >
          <el-breadcrumb-item>文档编辑</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="text item">
        <el-form
          :model="editForm"
          :rules="rules"
          ref="editForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- ID -->
          <el-form-item label="ID">
            <el-input v-model="editForm.id"></el-input>
          </el-form-item>
          <!-- 标题 -->
          <el-form-item label="文档标题" prop="title">
            <el-input v-model="editForm.title"></el-input>
          </el-form-item>
          <!-- 作者 -->
          <el-form-item label="文档作者" prop="author">
            <el-input v-model="editForm.author"></el-input>
          </el-form-item>
          <!-- 发布日期 -->
          <el-form-item label="发布时间" prop="inputtime">
            <!-- datatime组件 -->
            <el-date-picker
              value-format="yyyy-MM-dd HH:mm:ss"
              size="large"
              v-model="editForm.inputtime"
              type="datetime"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
          <!-- 文档内容 -->
          <el-form-item label="内容" prop="content">
            <!-- 
              改成富文本编辑器
              ToolBar：工具条
                editor：编辑器对象
                defaultConfig：默认（工具条）配置
              Editor：编辑区域
                defaultConfig：默认（编辑器）配置
                v-model：编辑器双向绑定的数据
                onCreated：富文本编辑器自带的生命周期事件，表编辑器创建完毕时的回调函数
             -->
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="editForm.content"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="onCreated"
              />
            </div>
          </el-form-item>
          <!-- 编辑按钮和重置按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submitForm('editForm')"
              >编辑</el-button
            >
            <el-button @click="resetForm('editForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from "@/api/article.js";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
export default {
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: "<p>hello</p>",
      toolbarConfig: {},
      editorConfig: { placeholder: "请输入内容..." },
      mode: "default", // or 'simple'
      // 回显时候文档对象
      editForm: {
        id: "",
        title: "",
        author: "",
        inputtime: "",
        content: "",
      },
      // 编辑验证规则：
      rules: {
        title: [
          //三个属性意思  required表示是否必须填写  message表示错误提示信息 trigger表示触发条件
          {
            required: true,
            message: "请输入标题",
            trigger: "blur",
          },
          //用户名 3-12个可用字符
          {
            pattern: /^[a-zA-Z\u4e00-\u9fa5\d_|,?:]{2,50}$/,
            message: "标题格式不正确",
            trigger: "blur",
          },
        ],
        author: [
          //三个属性意思  required表示是否必须填写  message表示错误提示信息 trigger表示触发条件
          {
            required: true,
            message: "请输入作者",
            trigger: "blur",
          },
          //用户名 3-12个可用字符
          {
            pattern: /^[a-zA-Z\u4e00-\u9fa5\d_]{2,20}$/,
            message: "作者格式不正确",
            trigger: "blur",
          },
        ],
        inputtime: [
          { required: true, message: "请输入发布时间", trigger: "change" },
        ],
        content: [
          //三个属性意思  required表示是否必须填写  message表示错误提示信息 trigger表示触发条件
          {
            required: true,
            message: "请输入备注信息",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 编写验证富文本编辑器是否为空的方法
    validEditor() {
      if (this.editForm.content == "<p><br></p>") {
        // 代表编辑器是空
        this.$message({
          type: "warning",
          message: "文字内容不能为空",
        });
        return false;
      } else {
        // 编辑器不能为空
        return true;
      }
    },
    // 创建Editor对象
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.validEditor()) {
            // 验证通过
            this.$message({
              type: "success",
              message: "验证通过",
            });
            // 向服务器发起请求
            request
              .updateArticle(this.editForm)
              .then((r) => {
                console.log(r);
                if (r.data.code === 0) {
                  // 判断成功与否，给出消息提示
                  this.$message({
                    message: "编辑文档成功",
                    type: "success",
                  });
                  // 跳转到展示页面
                  this.$router.push("/index/art-list");
                } else {
                  this.$message.error("编辑文档失败");
                }
              })
              .catch((e) => {
                console.log(e);
                this.$message.error("编辑文档请求异常");
              });
          } else {
            console.log("error submit!!");
            return false;
          }
        }
      });
    },
    resetForm(formName) {
      this.showArticle();
    },
    // 回显数据
    showArticle() {
      // 1.获取路由参数
      let id = this.$route.query.id;
      console.log(id);
      // 2.发请求获取当前文档信息
      request
        .getone(id)
        .then((r) => {
          console.log(r);
          // 将服务器获取的数据传递给界面状态值
          this.editForm = r.data;
        })
        .catch((e) => {
          console.log(e);
        });
    },
  },
  created() {
    // 初始化调用回显
    this.showArticle();
  },
  mounted() {},
};
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}
</style>
